package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Role;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/role")
@SuppressWarnings({"unchecked", "rawtypes"}) //上述注解是jse提供的注解。作用是屏蔽一些无关紧要的警告。使开发者能看到一些他们真正关心的警告。从而提高开发者的效率
public class RoleController extends BaseController {

    @Reference
    private RoleService roleService;

    @Reference
    private PermissionService permissionService;


    private final static String PAGE_INDEX = "role/index";
    private final static String PAGE_CREATE = "role/create";
    private final static String PAGE_EDIT = "role/edit";
    private final static String PAGE_SUCCESS = "common/successPage";

    private final static String PAGE_ASSGIN_SHOW = "role/assginShow";

    /**
     * 列表
     *
     * @param model
     * @return
     */
    @RequestMapping
    @PreAuthorize("hasAuthority('role.show')")
    public String index(ModelMap model, HttpServletRequest request) {
        //实现分页
        Map<String, Object> filters = getFilters(request);
//        List<Role> list = roleService.findAll();
        PageInfo<Role> page = roleService.findPage(filters);
        model.addAttribute("page", page);
        model.addAttribute("filters", filters);
        return PAGE_INDEX;
    }
    //主要获取请求中分页的参数
//    private Map<String, Object> getFilters(HttpServletRequest request) {
//        //获取表单中所有具有name属性的表单对象，返回值为Enumeration
//        Enumeration parameterNames = request.getParameterNames();
//        Map<String, Object> filters = new HashMap<>();
//        //效验前端传递过来的参数是否有值
//        while (parameterNames != null && parameterNames.hasMoreElements()) {
//            String parameName = (String) parameterNames.nextElement();
//            //获取值
//            String[] Values = request.getParameterValues(parameName);
//            filters.put(parameName, Values[0]);
//        }
//        //如果没有pageNum参数，则给pageNum为1
//        if (!filters.containsKey("pageNum")) {
//            filters.put("pageNum", 1);
//        }
//        //如果没有pageSize参数，则给pageSize为1
//        if (!filters.containsKey("pageSize")) {
//            filters.put("pageSize", 3);
//        }
//        return filters;
//    }

    /**
     * 添加页面
     *
     * @param model
     * @return
     */
    @GetMapping("/create")
    @PreAuthorize("hasAuthority('role.create')")
    public String create(ModelMap model) {
        return PAGE_CREATE;
    }

    /**
     * 保存添加功能
     *
     * @param role
     * @param response
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('role.create')")
    public String save(Role role, HttpServletResponse response) {
        roleService.insert(role);
        return PAGE_SUCCESS;
    }

    /**
     * 用于回显表单
     *
     * @param modelMap
     * @param id
     * @return
     */
    @GetMapping("/edit/{id}")
    @PreAuthorize("hasAuthority('role.edit')")
    public String edit(ModelMap modelMap, @PathVariable Long id) {
        Role role = roleService.getById(id);
        modelMap.addAttribute("role", role);
        return PAGE_EDIT;
    }

    /**
     * 更新数据
     *
     * @param role
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('role.edit')")
    public String update(Role role) {
        roleService.update(role);
        return PAGE_SUCCESS;
    }

    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('role.delete')")
    public String delete(@PathVariable Long id) {
        roleService.delete(id);
        return "redirect:/role";
    }

    /**
     * 进入分配权限页面
     *
     * @param modelMap
     * @param roleId
     * @return
     */
    @GetMapping("/assignShow/{roleId}")
    @PreAuthorize("hasAuthority('role.assgin')")
    public String assignShow(ModelMap modelMap, @PathVariable Long roleId) {
        //调用PermissionService中查询所有权限方法
        List<Map<String, Object>> zNodes = permissionService.findPermissionByRoleId(roleId);
        modelMap.addAttribute("zNodes", zNodes);
        modelMap.addAttribute("roleId", roleId);
        return PAGE_ASSGIN_SHOW;
    }

    /**
     * 给角色分配权限
     * @param roleId
     * @param permissionIds
     * @return
     */
    @PostMapping("/assignPermission")
    @PreAuthorize("hasAuthority('role.assgin')")
    public String assignPermission(Long roleId, Long[] permissionIds) {
        //调用PermissionService中分配权限方法
        permissionService.saveRolePermissionRealtionShip(roleId, permissionIds);
        return PAGE_SUCCESS;
    }
}
